import {createRouter, createWebHistory} from 'vue-router'
import HomeView from '../views/HomeView.vue'
import store from "@/store";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/login',
    },
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      children: [
        {
          path: '/home',
          name: 'index',
          component: () => import('../views/IndexView.vue')
        },
        {
          path: '/mine',
          name: 'Mine',
          component: () => import('../views/MineView.vue')
        },
        {
          path: '/searchResults',
          name: 'searchResults',
          component: () => import('../views/SearchResultsView.vue'),
        },
        {
          path: '/detail',
          name: 'detail',
          component: () => import('../views/DetailView.vue'),
        }
      ]
    },
    {
      path: '/login',
      name: 'login',
      component: () => import('../views/LoginView.vue')
    },
  ]
})

router.beforeEach((to, from, next) => {
  const isAuthenticated = checkUserAuthentication(); // 自定义函数检查用户认证状态

  if (to.path === '/login' && isAuthenticated) {
    // 如果用户已登录，重定向到仪表板
    next('/home');
  } else if (to.path !== '/login' && !isAuthenticated) {
    // 如果用户未登录且不是前往登录页，重定向到登录页
    next('/');
  } else {
    next(); // 放行路由
  }
})

function checkUserAuthentication() {
  return !(store.state.token === '' || store.state.token === null);
}

export default router
